﻿using languageSite.Helpers;
using languageSite.Options;
using languageSite.ViewModels.Common;
using languageSite.ViewModels.Translate;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using RestSharp;
using System.Web;

namespace languageSite.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class TranslateController : ControllerBase
    {
        private readonly BDOption bdOption;
        public TranslateController(IOptions<BDOption> options)
        {
            this.bdOption = options.Value;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return Ok();
        }

        [HttpPost]
        public ResModel<string> GetOneText(GetTextReq req)
        {
            return new ResModel<string>() { data = GetText(req.from, req.query, req.to).FirstOrDefault() ?? "" };

        }
        [HttpPost]
        public ResModel<List<string>> GetManyText(GetManyTextReq req)
        {
            return new ResModel<List<string>> () { data = GetText(req.from, req.query,  req.to.ToArray()) };
        }


        private List<string> GetText(string from,string query, params string[] to)
        {
            var res = new List<string>();
            if (to.Count() == 0 || string.IsNullOrEmpty(query))
            {
                return res;
            }
            // 原文
            string q = query;
            string appId = bdOption.appId;
            Random rd = new Random();
            // 改成您的密钥
            string secretKey = bdOption.secretKey;
            
            foreach (var t in to)
            {
                string salt = rd.Next(100000).ToString();
                string sign = StringHelper.EncryptString(appId + q + salt + secretKey);
                string url = bdOption.url;

                url += "q=" + HttpUtility.UrlEncode(q);
                url += "&from=" + from;
                url += "&to=" + t;
                url += "&appid=" + appId;
                url += "&salt=" + salt;
                url += "&sign=" + sign;
                var resObj = HttpHelper.GetTranslateString(url);
                res.Add(resObj??"");
            }
            return res;
        }
    }
}
